﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLZJFurnitureSCM.Model;
using QLZJFurnitureSCM.BLL;
using System.Threading;

namespace QLZJFurnitureSCM.WinForm
{
    public partial class FrmMain : Form
    {
        public FrmLogin frmLogin = null;
        private FurnitureTypeService furnitureTypeService = null;
        public static User user = null;
        private string userName = string.Empty;
        private string userPwd = string.Empty;
        private List<Order> lstOrderUnpay = null;

        public FrmMain()
        {
            //CheckForIllegalCrossThreadCalls = false;
            //this.StartPosition = FormStartPosition.CenterScreen;
            //if (frmLogin == null)
                frmLogin = new FrmLogin();
            CheckLogin();
        }

        #region Login before Show FrmMain
        private void init()
        {
            CheckLogin();
        }

        private void CheckLogin()
        {
            if (this.Login())
            {
                //Find User
                user = new User(userName, userPwd);
                UserService userService = new UserService();
                user = userService.UserLogin(user);
                if (user != null)
                {
                    //MessageBox.Show(string.Format("{0}:{1}:{2}:{3}.", user.UserId, user.UserName, user.UserPwd, user.UserRole));
                    InitializeComponent();
                    //this.StartPosition = FormStartPosition.CenterScreen;
                    this.WindowState = FormWindowState.Maximized;
                    this.lblLoginUserNickName.Text = user.NickName;
                    timerTime.Start();
                    this.Show();
                    frmLogin.Dispose();
                    if(user.UserRole == 1)
                        this.账号管理ToolStripMenuItem.Visible = true;
                    CheckUnPayOrder();//new Thread(new ThreadStart(CheckUnPayOrder)).Start();
                }
                else
                {
                    MessageBox.Show("登录失败.");
                    CheckLogin();
                }
                //MessageBox.Show(string.Format("userName:{0} Password:{1} Logging...", userName, userPwd));
                
                //this.Visible = true;
            }
            else
                Environment.Exit(0);
        }

        public bool Login()
        {
            frmLogin.ShowDialog(this);

            if (frmLogin.DialogResult == DialogResult.OK)
            {
                userName = frmLogin.userName;
                userPwd = frmLogin.userPwd;
                if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(userPwd))
                    CheckLogin();
                else
                    return true;
            }
            return false;
        }

        #endregion

        #region CheckUnpayOrder
        private void CheckUnPayOrder()
        {
            lstOrderUnpay = new OrderService().FindUnPayOrder();
            if (lstOrderUnpay.Count > 0)
            {
                this.toolStripStatusLabelOrder.Text = string.Format("还有{0}张订单未结算, 点此查看进行操作.", lstOrderUnpay.Count);
                this.toolStripStatusLabelOrder.ForeColor = Color.Red;
                this.toolStripStatusLabelOrder.Click += new EventHandler(toolStripStatusLabelOrder_Click);
            }
        }

        private void toolStripStatusLabelOrder_Click(object sender, EventArgs e)
        {
            if(lstOrderUnpay == null)
                lstOrderUnpay = new OrderService().FindUnPayOrder();
            int count = lstOrderUnpay.Count;
            FrmSaleRecord frmSaleRecord = new FrmSaleRecord(ref count);
            frmSaleRecord.StartPosition = FormStartPosition.CenterParent;
            frmSaleRecord.ShowDialog(this);
            frmSaleRecord.Dispose();
            if (count > 0)
                this.toolStripStatusLabelOrder.Text = string.Format("还有{0}张订单未结算, 点此查看进行操作.", count);
            else
            {
                this.toolStripStatusLabelOrder.Text = "";
            }
            lstOrderUnpay = null;
        }
        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'furnitureDataSet.FurnitureType' table. You can move, or remove it, as needed.
            库存ToolStripMenuItem_Click(sender, e);
        }

        private void FrmMain_Shown(object sender, EventArgs e)
        {

        }

        private int typeIdLast = -1;
        private TreeView treeViewType = null;
        private ContextMenuStrip ctxMenuStripTreeView = null;

        private void typeMgrTreeView()
        {
            this.splitContainerTop.Panel1.Controls.Clear();

            treeViewType = new TreeView();
            
            //toolStripFrmMain.Height
            //treeViewType.Parent = this.panelMain;
            //treeViewType.Parent = this.splitContainerMain.Panel1;
            treeViewType.Parent = this.splitContainerTop.Panel1;
            treeViewType.Dock = DockStyle.Fill;
            //treeViewType.BackColor = SystemColors.AppWorkspace;
            //treeViewType.Location = new Point(menuStripFrmMain.Location.X, menuStripFrmMain.Height);
            //treeViewType.Anchor = AnchorStyles.None;
            //treeViewType.Bounds = new Rectangle(new Point(toolStripFrmMain.Location.X, toolStripFrmMain.Height), new Size(100, 100));
            //treeViewType.Dock = DockStyle.Fill;
            //treeViewType.Dock = DockStyle.Bottom;
            ctxMenuStripTreeView = new ContextMenuStrip();
            treeViewType.ContextMenuStrip = ctxMenuStripTreeView;
            //ctxMenuStripTreeView.Parent = treeViewType;
            ToolStripMenuItem tsmiAdd = new ToolStripMenuItem();;
            tsmiAdd.Text = "添加新分类";
            tsmiAdd.Click += new EventHandler(tsmiAdd_Click);
            ctxMenuStripTreeView.Items.Add(tsmiAdd);

            ToolStripMenuItem tsmiDelete = new ToolStripMenuItem();
            tsmiDelete.Text = "删除当前分类";
            tsmiDelete.Click += new EventHandler(tsmiDelete_Click);
            ctxMenuStripTreeView.Items.Add(tsmiDelete);

            ToolStripMenuItem tsmiRename = new ToolStripMenuItem();
            tsmiRename.Text = "重命名此分类名称";
            tsmiRename.Click += new EventHandler(tsmiRename_Click);
            ctxMenuStripTreeView.Items.Add(tsmiRename);

            ToolStripMenuItem tsmiAddProduct = new ToolStripMenuItem();
            tsmiAddProduct.Text = "添加新产品";
            tsmiAddProduct.Click += new EventHandler(tsmiAddProduct_Click);
            ctxMenuStripTreeView.Items.Add(tsmiAddProduct);
            //this.treeView1.Nodes.Clear();
            
            //this.treeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView_NodeMouseClick);
            treeViewType.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeView_NodeMouseClick);
            treeViewType.AllowDrop = true;
            treeViewType.DragDrop += new DragEventHandler(treeViewType_DragDrop);;
            treeViewType.ItemDrag += new ItemDragEventHandler(treeViewType_ItemDrag);
            treeViewType.DragEnter += new DragEventHandler(treeViewType_DragEnter);
            //treeViewType.KeyPress += new KeyPressEventHandler(treeViewType_KeyPress);
            treeViewType.KeyDown += new KeyEventHandler(treeViewType_KeyDown);
            //treeViewType.MouseClick += new MouseEventHandler(treeViewType_MouseClick);
            DrawAllFurnitureTypesInTreeView();
        }

        private void DrawAllFurnitureTypesInTreeView()
        {
            
            furnitureTypeService = new FurnitureTypeService();
            List<FurnitureType> lstFurnitureType = furnitureTypeService.ReadAll();

            TreeNode nodeRoot = new TreeNode("所有分类");
            nodeRoot.Name = "0";
            treeViewType.Nodes.Add(nodeRoot);

            if (lstFurnitureType.Count > 0)
            {
                //(from furniture in lstFurnitureType select furniture).ToList();
                //GetNodes(lstFurnitureType, treeView1.Nodes);
                GetNodes(lstFurnitureType, nodeRoot.Nodes);

                typeIdLast = lstFurnitureType.Last().TypeId;

                List<FurnitureType> lstUnRootType = lstFurnitureType.FindAll(EqualsTopType);
                //List<int> lstSubTypeId = new List<int>();
                foreach (FurnitureType type in lstUnRootType)
                {
                    //lstSubTypeId.Add(type.TypeId);
                    if (nodeRoot.Nodes.ContainsKey(type.TypeId.ToString()))
                        nodeRoot.Nodes.RemoveByKey(type.TypeId.ToString());
                    /*
                    if(treeView1.Nodes.ContainsKey(type.TypeId.ToString()))
                        treeView1.Nodes.RemoveByKey(type.TypeId.ToString());*/
                }
                //treeView1.ExpandAll();
                //MessageBox.Show("height:" + toolStripFrmMain.Height * 2);
                //treeViewType.Location = new Point(menuStripFrmMain.Location.X, this.MainMenuStrip.Height);

                treeViewType.ExpandAll();
            }

            this.splitContainerMain.Panel2.Controls.Clear();
        }

        //private TreeNode currentSelectNode = null;


        #region TreeView Event

        private void treeViewType_DragDrop(object sender, DragEventArgs e)
        {
            Point targetPoint = treeViewType.PointToClient(new Point(e.X, e.Y));
            TreeNode targetNode = treeViewType.GetNodeAt(targetPoint);
            if (null == targetNode)
                return;
            TreeNode draggedNode = (TreeNode)e.Data.GetData(typeof(TreeNode));
            if (!draggedNode.Equals(targetNode) && !ContainsNode(draggedNode, targetNode))
            {
                //更新到数据库.
                if(furnitureTypeService.UpdateFurnitureUpType(int.Parse(draggedNode.Name), int.Parse(targetNode.Name)))
                {
                    //设置目标分类前景色
                    //targetNode.ForeColor = Color.Blue;
                    targetNode.ExpandAll();
                    draggedNode.Remove();
                    targetNode.Nodes.Add(draggedNode);
                }
            }
        }

        private void treeViewType_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.AllowedEffect;
        }

        private bool ContainsNode(TreeNode node1, TreeNode node2)
        {
            // Check the parent node of the second node.
            if (node2.Parent == null) return false;
            if (node2.Parent.Equals(node1)) return true;

            // If the parent node is not null or equal to the first node, 
            // call the ContainsNode method recursively using the parent of 
            // the second node.
            return ContainsNode(node1, node2.Parent);
        }

        private void treeViewType_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void treeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs  e)
        {
            if(e.Button == MouseButtons.Left)
            {
                string keyStr = e.Node.Name;

                //未绑定数据.
                //this.splitContainerMain.Panel2.Update();
                  
                if (!string.IsNullOrEmpty(keyStr))
                {
                    int productType = int.Parse(keyStr);

                    //string.Format("select * from products where productType = '{0}';", key);
                    /*
                    productsDgv = new DataGridView();
                    productsDgv.Name = "productsDgv";
                    
                    productsDgv.DataSource = lstProducts;
                    productsDgv.Parent = this.splitContainerTop.Panel2;
                    productsDgv.Dock = DockStyle.Fill;
                    productsDgv.Update();*/

                    //lstProducts = productService.FindProductsByProductType(productType);
                    dt = productService.ReadInDataTableByProductType(productType);
                    DrawProductsDgv();
                }
            }
            if (e.Button == MouseButtons.Right)
            {
                //this.treeView1.SelectedNode = e.Node;
                treeViewType.SelectedNode = e.Node;
                //this.contextMenuStrip1.Show(this.treeView1, e.X, e.Y);
                this.ctxMenuStripTreeView.Show(this.treeViewType, e.X, e.Y);
            }
        }

        private void treeViewType_KeyDown(object sender, KeyEventArgs e)
        {
            if(this.treeViewType.SelectedNode != null)
            {
                if(!"0".Equals(this.treeViewType.SelectedNode.Name))
                {
                    if (e.KeyCode == Keys.F2)//113 = Keys.F2
                    {
                        /*
                        Thread thread = new Thread(new ThreadStart(typeMgrRename));
                        thread.Start();*/
                        typeMgrRename();
                    }
                }
            }
        }

        private void treeViewType_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                this.treeViewType.SelectedNode = ((TreeView)sender).SelectedNode;
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool EqualsTopType(FurnitureType type)
        {
            return type.TypeUpId != 0;
        }

        //private int i = 0;
        private List<FurnitureType> lstSubType = null;
        private void GetNodes(List<FurnitureType> lstFurnitureType, TreeNodeCollection nodes)
        {
            //TestNodes(treeView1.Nodes);
            
            TreeNode node = null;
            lstSubType = new List<FurnitureType>();
            foreach (FurnitureType type in lstFurnitureType)
            {
                //TestNodes(treeView1.Nodes);
                node = new TreeNode();
                node.Text = type.TypeName;
                node.Name = type.TypeId.ToString();
                node.Tag = type.TypeUpId;
                //if (CheckNodeExits(node))
                //    continue;
                nodes.Add(node);
               
                //lstSubType = furnitureTypeService.FindFurnitureSubTypeByTypeUpId(type.TypeUpId);
                lstSubType = furnitureTypeService.FindFurnitureUpTypeByTypeId(type.TypeId);
                if (lstSubType == null)
                    continue;
                GetNodes(lstSubType, node.Nodes);
                //string.Format("select * from furnitureType where typeUpId = {0}", type.TypeUpId);
            }
        }

        /*
        public bool CheckNodeExits(TreeNode node)
        {
            //Console.WriteLine(treeView1.Nodes.IndexOf(node));
            return false;
        }*/

        /*
        private void TestNodes(TreeNodeCollection nodes)
        {
            i++;
            foreach (TreeNode node in nodes)
            {
                Console.WriteLine(string.Format("{0}:{1}.", i, node.Text));
                //TestNodes(node.Nodes);
            }
        }*/

        /*
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            
             * Normal
            MessageBox.Show(this.treeView1.SelectedNode.Text);
            typeIdLast++;
            TreeNode node = new TreeNode("新节点");
            this.treeView1.SelectedNode.Nodes.Add(node);
            this.treeView1.SelectedNode = node;
            //this.treeView1.Refresh();
            //MessageBox.Show(this.treeView1.SelectedNode.Name);
        }*/


        #region TreeView ToolStripMenuItem Click Event

        private void tsmiAdd_Click(object sender, EventArgs e)
        {
            typeMgrEdit();

            //MessageBox.Show(this.treeViewType.SelectedNode.Text);
            /* Support
            typeIdLast++;
            TreeNode node = new TreeNode("新节点");
            this.treeViewType.SelectedNode.Nodes.Add(node);
            this.treeViewType.SelectedNode = node;*/
            //this.treeView1.Refresh();
            //MessageBox.Show(this.treeView1.SelectedNode.Name);
        }

        private void tsmiDelete_Click(object sender, EventArgs e)
        {
            TreeNode node = this.treeViewType.SelectedNode;
            if (null != node)
            {
                if (!string.IsNullOrEmpty(node.Name))
                {
                    FurnitureType type = new FurnitureType();
                    type.TypeId = int.Parse(node.Name);
                    Console.WriteLine("Remove: " + type.TypeId);
                    //添加储存过程或者sql语句删除对应商品.

                    DeleteOwnerNodes(node);
                    node.Remove();

                    //if(furnitureTypeService.Delete(type))
                    //    node.Remove();  
                }
            }
        }

        private void DeleteOwnerNodes(TreeNode root)
        {
            FurnitureType type = new FurnitureType();
            TreeNodeCollection treeNodeCollection = root.Nodes;
            type.TypeId = int.Parse(root.Name);
            furnitureTypeService.Delete(type);
            foreach (TreeNode node in treeNodeCollection)
            {
                type.TypeId = int.Parse(node.Name);
                if (furnitureTypeService.Delete(type))
                    DeleteOwnerNodes(node);
            }
            
        }

        private void tsmiRename_Click(object sender, EventArgs e)
        {
            typeMgrRename();
            /*
            TreeNode node = this.treeViewType.SelectedNode;
            //Show Panel
            if (null != node)
            {
                if (!string.IsNullOrEmpty(node.Name))
                {
                    FurnitureType type = new FurnitureType();
                    type.TypeId = int.Parse(node.Name);
                    Console.WriteLine("Remove: " + type.TypeId);
                    //UpdateNode
                    node.Text = "";
                }

            }*/
        }

        
        private int furnitureTypeId = -1;
        /*
        private TextBox txtProductName = null;
        private TextBox txtProductCount = null;
        private TextBox txtProductPricePurchase = null;
        private TextBox txtProductPriceSale = null;
        private TextBox txtProductDescription = null;
        */
        UserControlNewProduct ucNewProduct = null;
        private void tsmiAddProduct_Click(object sender, EventArgs e)
        {
            this.splitContainerMain.Panel2.Controls.Clear();
            string typeName = this.treeViewType.SelectedNode.Text;
            if ("所有分类".Equals(typeName))
            {
                MessageBox.Show("先选择正确的分类再添加商品.");
                return;
            }
            ucNewProduct = new UserControlNewProduct(typeName);
            ucNewProduct.Parent = this.splitContainerMain.Panel2;
            ucNewProduct.btnProductAdd.Click += new EventHandler(btnProductAdd_Click);
            ucNewProduct.btnCancel.Click += new EventHandler(btnSplitMainPanel2Cancel_Click);
        }

        #region Without the productPriceSale & productCount & productDimension
        private void AddProductInThePanelBefore()
        {
            this.splitContainerMain.Panel2.Controls.Clear();
            Rectangle rect = this.splitContainerMain.Panel2.Bounds;

            //this.splitContainerMain.Panel2.Padding = new Padding(10);
            Label lblAdd = new Label();
            //productType = int.Parse(this.treeViewType.SelectedNode.Name);
            lblAdd.Text = "类别: " + this.treeViewType.SelectedNode.Text;
            lblAdd.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblAdd.Padding = new Padding(5, 5, 0, 5);
            int height = lblAdd.Height;
            int split = 0;
            split = rect.Height / 2 - lblAdd.Height;
            lblAdd.Location = new Point(split, split);
            this.splitContainerMain.Panel2.Controls.Add(lblAdd);

            Label lblProductName = new Label();
            lblProductName.Text = "商品名称:";
            lblProductName.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblProductName.Padding = new Padding(5, 5, 0, 5);
            split = lblProductName.Height - lblAdd.Height;
            if (split != 0)
                split = split / 2;
            this.splitContainerMain.Panel2.Controls.Add(lblProductName);
            lblProductName.Location = new Point(lblAdd.Location.X + lblAdd.Width + 5, lblAdd.Location.Y - split);

            TextBox txtProductName = new TextBox();
            txtProductName.Parent = this.splitContainerMain.Panel2;
            split = txtProductName.Height - lblProductName.Height;
            if (split != 0)
                split = split / 2;
            txtProductName.Location = new Point(lblProductName.Location.X + lblProductName.Width + 5, lblProductName.Location.Y - split);

            Label lblProductPrice = new Label();
            lblProductPrice.Text = "价格:";
            lblProductPrice.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblProductPrice.Padding = new Padding(5, 5, 0, 5);
            split = lblProductPrice.Height - txtProductName.Height;
            if (split != 0)
                split = split / 2;
            this.splitContainerMain.Panel2.Controls.Add(lblProductPrice);
            lblProductPrice.Location = new Point(txtProductName.Location.X + txtProductName.Width + 5, txtProductName.Location.Y - split);

            TextBox txtProductPrice = new TextBox();
            txtProductPrice.Parent = this.splitContainerMain.Panel2;
            split = txtProductPrice.Height - lblProductPrice.Height;
            if (split != 0)
                split = split / 2;
            txtProductPrice.Location = new Point(lblProductPrice.Location.X + lblProductPrice.Width + 5, lblProductPrice.Location.Y - split);
            txtProductPrice.KeyPress += new KeyPressEventHandler(txtProductPrice_KeyPress);

            Label lblProductDescription = new Label();
            lblProductDescription.Text = "描述:";
            lblProductDescription.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblProductDescription.Padding = new Padding(5, 5, 0, 5);
            split = lblProductDescription.Height - txtProductPrice.Height;
            if (split != 0)
                split = split / 2;
            this.splitContainerMain.Panel2.Controls.Add(lblProductDescription);
            lblProductDescription.Location = new Point(txtProductPrice.Location.X + txtProductPrice.Width + 5, txtProductPrice.Location.Y - split);

            TextBox txtProductDescription = new TextBox();
            txtProductDescription.Parent = this.splitContainerMain.Panel2;
            txtProductDescription.Width = 200;
            split = txtProductDescription.Height - lblProductDescription.Height;
            if (split != 0)
                split = split / 2;
            txtProductDescription.Location = new Point(lblProductDescription.Location.X + lblProductDescription.Width + 5, lblProductDescription.Location.Y - split);

            Button btnTypeAdd = new Button();
            btnTypeAdd.Parent = this.splitContainerMain.Panel2;
            btnTypeAdd.Text = "添加";
            split = btnTypeAdd.Height - txtProductDescription.Height;
            if (split != 0)
                split = split / 2;
            btnTypeAdd.Location = new Point(txtProductDescription.Location.X + txtProductDescription.Width + 15, txtProductDescription.Location.Y - split);

            //MessageBox.Show(lblAdd.Location.Y + ":" + txtTypeName.Location.Y + ":" + btnTypeAdd.Location.Y);
            btnTypeAdd.Click += new EventHandler(btnProductAdd_Click);

            txtProductName.Focus();
        }
        #endregion

        #endregion

        /*
        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            Form frmAdd = new Form();
            frmAdd.MdiParent= this;
            //this.AddOwnedForm(frmAdd);
            frmAdd.Show();
        }*/

        #region FurnitureType Manager

        private TextBox txtTypeName = null;

        private void typeMgrEdit()
        {
            this.splitContainerMain.Panel2.Controls.Clear();
            //this.splitContainerMain.Panel2.Padding = new Padding(10);
            Label lblAdd = new Label();
            lblAdd.Text = "类别: ";
            lblAdd.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblAdd.Padding = new Padding(10, 10, 0, 5);
            int height = lblAdd.Height;
            int split = 0;
            this.splitContainerMain.Panel2.Controls.Add(lblAdd);

            txtTypeName = new TextBox();
            txtTypeName.Parent = this.splitContainerMain.Panel2;
            split = txtTypeName.Height - lblAdd.Height;
            if (split != 0)
                split = split / 2;
            txtTypeName.Location = new Point(lblAdd.Location.X + lblAdd.Width + 10, lblAdd.Location.Y - split);
            
            Button btnTypeAdd = new Button();
            btnTypeAdd.Parent = this.splitContainerMain.Panel2;
            btnTypeAdd.Text = "添加";
            split = btnTypeAdd.Height - txtTypeName.Height;
            if (split != 0)
                split = split / 2;
            btnTypeAdd.Location = new Point(txtTypeName.Location.X + txtTypeName.Width + 10, txtTypeName.Location.Y - split);

            btnTypeAdd.Click += new EventHandler(btnTypeAdd_Click);

            Button btnCancel = new Button();
            btnCancel.Parent = this.splitContainerMain.Panel2;
            btnCancel.Text = "取消";
            split = btnCancel.Height - btnTypeAdd.Height;
            if (split != 0)
                split = split / 2;
            btnCancel.Location = new Point(btnTypeAdd.Location.X + btnTypeAdd.Width + 10, btnTypeAdd.Location.Y - split);

            btnCancel.Click += new EventHandler(btnSplitMainPanel2Cancel_Click);

            //MessageBox.Show(lblAdd.Location.Y + ":" + txtTypeName.Location.Y + ":" + btnTypeAdd.Location.Y);
            

            this.txtTypeName.Focus();
        }
    

        private void typeMgrRename()
        {
            this.splitContainerMain.Panel2.Controls.Clear();
            //this.splitContainerMain.Panel2.Padding = new Padding(10);
            Label lblAdd = new Label();
            lblAdd.Text = "类别: " + this.treeViewType.SelectedNode.Text + "  重命名为: ";
            furnitureTypeId = int.Parse(this.treeViewType.SelectedNode.Name);
            lblAdd.AutoSize = true;
            //lblAdd.Dock = DockStyle.Left;
            lblAdd.Padding = new Padding(5, 5, 0, 5);
            int height = lblAdd.Height;
            int split = 0;
            this.splitContainerMain.Panel2.Controls.Add(lblAdd);

            txtTypeName = new TextBox();
            txtTypeName.Parent = this.splitContainerMain.Panel2;
            split = txtTypeName.Height - lblAdd.Height;
            if (split != 0)
                split = split / 2;

            txtTypeName.Location = new Point(lblAdd.Location.X + lblAdd.Width + 5, lblAdd.Location.Y - split);

            Button btnTypeRename = new Button();
            btnTypeRename.Parent = this.splitContainerMain.Panel2;
            btnTypeRename.Text = "更改";
            split = btnTypeRename.Height - txtTypeName.Height;
            if (split != 0)
                split = split / 2;
            btnTypeRename.Location = new Point(txtTypeName.Location.X + txtTypeName.Width + 5, txtTypeName.Location.Y - split);

            //MessageBox.Show(lblAdd.Location.Y + ":" + txtTypeName.Location.Y + ":" + btnTypeAdd.Location.Y);
            btnTypeRename.Click += new EventHandler(btnTypeRename_Click);

            this.txtTypeName.Focus();
        }

        #endregion

        #region SplitPanelMain.Panel2.Controls.Button Click Event & TextBox KeyPress Event

        private void txtProductPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.LastIndexOf('.') != -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
        }

        private void btnTypeAdd_Click(object sender, EventArgs e)
        {
            string typeName = this.txtTypeName.Text;
            if (string.IsNullOrEmpty(typeName))
                return;
            else
            {
                TreeNode node = new TreeNode(typeName);
                FurnitureType furnitureType = new FurnitureType();
                furnitureType.TypeName = typeName;
                if (null != this.treeViewType.SelectedNode)
                {
                    furnitureType.TypeUpId = int.Parse(this.treeViewType.SelectedNode.Name);
                }
                else
                {
                    //this.treeViewType.Nodes.Add(node);
                    //FurnitureType furnitureType = new FurnitureType();
                    //furnitureType.TypeName = typeName;
                    furnitureType.TypeUpId = 0;
                    //顶级添加.
                }
                furnitureType = furnitureTypeService.InsertFurnitureType(furnitureType);
                if (furnitureType.TypeId != 0)
                {
                    /*
                    this.treeViewType.SelectedNode.Nodes.Add(node);
                    this.treeViewType.SelectedNode = node;
                    node.ForeColor = Color.Red;
                    this.treeViewType.Focus();*/

                    typeMgrTreeView();
                }
                else
                    MessageBox.Show("更新失败");
            }
        }

        private void btnTypeRename_Click(object sender, EventArgs e)
        {
            string typeName = this.txtTypeName.Text;
            if(-1 != furnitureTypeId && !string.IsNullOrEmpty(typeName))
            {
                FurnitureType furnitureType = new FurnitureType();
                furnitureType.TypeId = furnitureTypeId;
                furnitureType.TypeName = typeName;
                if (furnitureTypeService.Update(furnitureType))
                {
                    typeMgrTreeView();
                }
            }
        }

        #region ProductAddInSplitPanel.Panel2
        /// <summary>
        /// ProductAddInSplitPanel.Panel2
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProductAdd_Click(object sender, EventArgs e){
            string productName = this.ucNewProduct.txtProductName.Text;
            string productPricePurchaseStr = this.ucNewProduct.txtProductPricePurchase.Text;
            string productPriceSaleStr = this.ucNewProduct.txtProductPriceSale.Text;
            string productDimension = this.ucNewProduct.txtDimension.Text;
            string productDescription = this.ucNewProduct.txtDescription.Text;
            int productCount = int.Parse(this.ucNewProduct.txtCount.Text);
            string productTypeName = this.treeViewType.SelectedNode.Text;
            int productType = int.Parse(this.treeViewType.SelectedNode.Name);
            
            //if(productType == 0)
            //    return;
            if (string.IsNullOrEmpty(productName) || string.IsNullOrEmpty(productPricePurchaseStr) || string.IsNullOrEmpty(productPriceSaleStr))
            {
                this.toolStripStatusLabelOPStatus.Text = "请填写正确信息.";
                return;
            }
            else
            {
                decimal productPricePurchase = decimal.Parse(productPricePurchaseStr);
                decimal productPriceSale = decimal.Parse(productPriceSaleStr);
                Product product = new Product();
                product.ProductName = productName;
                product.ProductType = productType;
                product.ProductDimension = productDimension;
                //检查名称是否存在于当前分类. 未实现
                if (!productService.CheckExistProductsByProductName(product))
                {
                    this.toolStripStatusLabelOPStatus.Text = "此产品已存在于当前分类, 请修改重试.";
                    return;
                }
                product.ProductCountAccumulate = productCount;
                product.ProductPricePurchase = productPricePurchase;
                product.ProductPriceSale = productPriceSale;
                product.ProductDescription = productDescription;
                //new add
                product.ProductCountSale = 0;
                product = productService.InsertProduct(product);
                if (product.ProductId > 0)
                {
                    Purchase purchase = new Purchase();
                    purchase.PurchaseByUser = user.NickName;
                    purchase.PurchaseCount = product.ProductCountAccumulate;
                    purchase.PurchaseDate = DateTime.Now;
                    purchase.PurchasePrice = product.ProductPricePurchase;
                    purchase.PurchaseProductType = productTypeName;
                    purchase.PurchaseProductName = product.ProductName;
                    purchase.PurchaseTotalPrice = product.ProductCountAccumulate * product.ProductPricePurchase;
                    PurchaseService purchaseService = new PurchaseService();
                    if(purchaseService.InsertPurchase(purchase).PurchaseId > 0)
                        UpdateProductDgv(product.ProductType);
                    
                }

                
                

                //添加完刷新当前类别的productDgv
                /*
                TreeNode node = new TreeNode(this.txtTypeName.Text);
                if (null != this.treeViewType.SelectedNode)
                {
                    this.treeViewType.SelectedNode.Nodes.Add(node);
                    this.treeViewType.SelectedNode = node;
                    node.ForeColor = Color.Red;
                    this.treeViewType.Focus();
                }
                else
                    this.treeViewType.Nodes.Add(node);*/
                this.toolStripStatusLabelOPStatus.Text = "添加成功.";
            }
        }
        #endregion

        #endregion

        private delegate void DrawProductDgvDelegate();

        private ProductService productService = new ProductService();
        //private List<Product> lstProducts = null;
        private DataGridView productsDgv = null;
        private void ShowProductsDgv(bool descSort)
        {
            /*
            productsDgv = new DataGridView();
            productsDgv.Name = "productsDgv";
            lstProducts = productService.ReadAll();
            productsDgv.DataSource = lstProducts;
            productsDgv.Parent = this.splitContainerTop.Panel2;
            productsDgv.Dock = DockStyle.Fill;
            productsDgv.Update();*/
            //lstProducts = productService.ReadAll();
            dt = productService.ReadInDataTable(descSort);
            
            this.Invoke( new DrawProductDgvDelegate(DrawProductsDgv));
            
        }

        private void SetDataGridViewRowColor()
        {
            if (this.productsDgv.Rows.Count != 0)
            {
                for (int i = 0; i < this.productsDgv.Rows.Count; )
                {
                    this.productsDgv.Rows[i].DefaultCellStyle.BackColor = SystemColors.ActiveBorder;//System.Drawing.Color.BurlyWood;
                    i += 2;
                }
                /*
                for (int i = 0; i <= this.productsDgv.Rows.Count - 3; )
                {
                    this.productsDgv.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.LightPink;
                    this.productsDgv.Rows[i + 1].DefaultCellStyle.BackColor = System.Drawing.Color.CornflowerBlue;
                    this.productsDgv.Rows[i + 2].DefaultCellStyle.BackColor = System.Drawing.Color.Green;
                    i += 3;
                }*/
            }
        }

        private DataTable dt = null;
        private void DrawProductsDgv()
        {
            //dt = new DataTable();
            if (productsDgv!=null)
                this.splitContainerTop.Panel2.Controls.Remove(productsDgv);
            productsDgv = new DataGridView();
            productsDgv.Name = "productsDgv";
            //productsDgv.DataSource = lstProducts;
            productsDgv.AllowUserToAddRows = false;
            productsDgv.DataSource = dt;
            /*
            DataColumn dtColm = new DataColumn();
            dtColm.DataType = typeof(Button);
            dtColm.Caption = "更新";
            dtColm.ColumnName = "btnColm";
            dt.Columns.Add(dtColm);*/
            //DataGridViewButtonColumn dgvBtnCol = new DataGridViewButtonColumn();
            //dt.Columns.Add("更新", typeof(DataGridViewButtonColumn));
            //double totalMS = (DateTime.Now - new DateTime(1970, 1, 1, 8, 0, 0)).TotalMilliseconds;
            
            productsDgv.Parent = this.splitContainerTop.Panel2;
            productsDgv.Dock = DockStyle.Fill;
            /*
            foreach(DataGridViewColumn col in productsDgv.Columns)
            {
                Console.WriteLine(col.Name);
            }*/

            productsDgv.Columns["productId"].Visible = false;
            productsDgv.Columns["productType"].Visible = false;
            productsDgv.Columns["productPricePurchase"].Visible = false;

            productsDgv.Columns["productName"].HeaderText = "名称";
            productsDgv.Columns["productDimension"].HeaderText = "规格";
            productsDgv.Columns["productPriceSale"].HeaderText = "售价";
            productsDgv.Columns["productCountAccumulate"].HeaderText = "库存";
            productsDgv.Columns["productCountSale"].HeaderText = "已售";
            productsDgv.Columns["productDescription"].HeaderText = "描述";

            foreach(DataGridViewColumn dgvColumn in productsDgv.Columns)
            {
                dgvColumn.ReadOnly = true;
            }

            productsDgv.Columns["productPriceSale"].ReadOnly = false;
            productsDgv.Columns["productPriceSale"].ValueType = typeof(decimal);

            productsDgv.Columns["productPriceSale"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            productsDgv.Columns["productCountAccumulate"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            productsDgv.Columns["productCountSale"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            productsDgv.Columns["productPriceSale"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            productsDgv.Columns["productCountAccumulate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;
            productsDgv.Columns["productCountSale"].AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader;

            productsDgv.EditMode = DataGridViewEditMode.EditOnEnter;
            productsDgv.AllowUserToResizeRows = false;
            productsDgv.RowHeadersVisible = false;
            productsDgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            productsDgv.BackgroundColor = SystemColors.Window;

            if(dt.Rows.Count > 0){
                //productsDgv.CellValueChanged += new DataGridViewCellEventHandler(productsDgv_CellValueChanged);
                /*
                DataGridViewButtonColumn dgvBtnAdd = new DataGridViewButtonColumn();
                dgvBtnAdd.Text = "添加";
                dgvBtnAdd.Name = "btnAdd";
                dgvBtnAdd.UseColumnTextForButtonValue = true;*/
                DataGridViewTextBoxColumn dgvTxtTotalValue = new DataGridViewTextBoxColumn();
                dgvTxtTotalValue.HeaderText = "合计";
                dgvTxtTotalValue.Name = "txtTotalValue";
                dgvTxtTotalValue.ReadOnly = true;
                dgvTxtTotalValue.ValueType = typeof(decimal);
                dgvTxtTotalValue.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                DataGridViewButtonColumn dgvBtnUpdate = new DataGridViewButtonColumn();
                dgvBtnUpdate.Text = "更新";
                dgvBtnUpdate.Name = "btnUpdate";
                dgvBtnUpdate.HeaderText = "";
                dgvBtnUpdate.UseColumnTextForButtonValue = true;
                dgvBtnUpdate.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
                DataGridViewButtonColumn dgvBtnDelete = new DataGridViewButtonColumn();
                dgvBtnDelete.Text = "删除";
                dgvBtnDelete.HeaderText = "";
                dgvBtnDelete.Name = "btnDelete";
                dgvBtnDelete.UseColumnTextForButtonValue = true;
                dgvBtnDelete.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
                DataGridViewButtonColumn dgvBtnSell = new DataGridViewButtonColumn();
                dgvBtnSell.Text = "出售";
                dgvBtnSell.HeaderText = "";
                dgvBtnSell.Name = "btnSell";
                dgvBtnSell.UseColumnTextForButtonValue = true;
                dgvBtnSell.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCellsExceptHeader;
                productsDgv.Columns.Add(dgvTxtTotalValue);
                productsDgv.Columns.AddRange(
                    new DataGridViewButtonColumn[] { //dgvBtnAdd, 
                    dgvBtnSell,
                    dgvBtnUpdate, dgvBtnDelete });

                int columnIndex = productsDgv.Columns["txtTotalValue"].Index;

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    productsDgv[columnIndex, i].Value = decimal.Parse(productsDgv["productPriceSale", i].Value.ToString()) * int.Parse(productsDgv["productCountAccumulate", i].Value.ToString());
                }
                productsDgv.Columns["txtTotalValue"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                productsDgv.CellContentClick += new DataGridViewCellEventHandler(productsDgv_CellContentClick);
                productsDgv.CellDoubleClick += new DataGridViewCellEventHandler(SellProduct);
                
                
            }
            //productsDgv.Columns["btnUpdateDataTable"].;
            /*  
            Button btnDgvUpdate = new Button();
            DataGridViewButtonColumn dgvBtnCol = new DataGridViewButtonColumn();
            dgvBtnCol.Text = "更新";

            productsDgv.Columns["btnColm"].CellType.Controls.Add(btnDgvUpdate);
             */

            //redraw
            //productsDgv.Refresh();
            SetDataGridViewRowColor();
        }

        private decimal saveCurrentPrice = -1;

        private void productsDgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (-1 == e.RowIndex)//header
                return;
            DataGridViewColumn dgvCol = productsDgv.Columns[e.ColumnIndex];
            DataGridViewRow dgvRow = productsDgv.Rows[e.RowIndex];
            if ("btnSell".Equals(dgvCol.Name))
            {
                SellProduct(sender, e);
            }
            else if ("btnUpdate".Equals(dgvCol.Name))
            {
                Product product = new Product();
                product.ProductId = (int)dgvRow.Cells["productId"].Value;
                product.ProductName = dgvRow.Cells["productName"].Value.ToString();
                product.ProductPriceSale = (decimal)dgvRow.Cells["productPriceSale"].Value;
                product.ProductType = (int)dgvRow.Cells["productType"].Value;
                if (productService.UpdateProduct(product))
                {
                    if (product.ProductPriceSale != saveCurrentPrice)
                    {
                        //添加价格修改记录
                        ProductPriceChange productPriceChange = new ProductPriceChange();
                        productPriceChange.ProductId = product.ProductId;
                        productPriceChange.ProductName = product.ProductName;
                        productPriceChange.ProductPrice = saveCurrentPrice;
                        productPriceChange.ProductPriceNow = product.ProductPriceSale;
                        productPriceChange.ProductChangeBy = FrmMain.user.NickName;
                        productPriceChange.ProductChangeDate = DateTime.Now;
                        ProductPriceChangeService productPriceChangeService = new ProductPriceChangeService();
                        productPriceChange = productPriceChangeService.InsertProductPriceChange(productPriceChange);
                        if (productPriceChange.ChangeId > 0)
                            toolStripStatusLabelOPStatus.Text = "添加成功.";
                        else
                            toolStripStatusLabelOPStatus.Text = "添加失败.";
                    }
                    dt = productService.ReadInDataTableByProductType(product.ProductType);
                    DrawProductsDgv();
                    toolStripStatusLabelOPStatus.Text = "更新成功.";
                }
                else
                    toolStripStatusLabelOPStatus.Text = "更新失败.";
                    //MessageBox.Show("Update Success.");
                /*
                foreach (DataRow dr in dt.Rows)
                {
                    foreach(object o in dr.ItemArray)
                    {
                        Console.WriteLine(o.ToString());
                    }
                    
                }*/
            }/*
            else if ("btnAdd".Equals(productsDgv.Columns[e.ColumnIndex].Name))
            {
                MessageBox.Show("Add Row[" + e.RowIndex + "]");
            }*/
            else if ("btnDelete".Equals(dgvCol.Name))
            {
                Product product = new Product();
                product.ProductId = (int)dgvRow.Cells["productId"].Value;
                if (productService.DeleteProduct(product))
                {
                    this.productsDgv.Rows.RemoveAt(e.RowIndex);
                    statusStripFrmMain.Text = "删除成功";
                }else
                {
                    statusStripFrmMain.Text = "删除失败,请重试.";
                }
                /*
            else
            {
                dt = productService.ReadInDataTableByProductType(product.ProductType);
                DrawProductsDgv();
            }*/
            }
            else if ("productPrice".Equals(dgvCol.Name))
            {
                saveCurrentPrice = decimal.Parse(dgvRow.Cells["productPrice"].Value.ToString());
                //productsDgv.CellDoubleClick += new DataGridViewCellEventHandler(productsDgv_CellDoubleClick);
            }
        }

        private Product productSell = null;
        private UserControlSellProduct ucSellProduct = null;
        private int rowIndexSell = -1;
        private void SellProduct(object sender, DataGridViewCellEventArgs e)
        {
            int count = int.Parse(productsDgv["productCountAccumulate", e.RowIndex].Value.ToString());
            if (count > 0)
            {
                rowIndexSell = e.RowIndex;
                
                this.splitContainerMain.Panel2.Controls.Clear();

                ucSellProduct = new UserControlSellProduct();
                ucSellProduct.Parent = this.splitContainerMain.Panel2;

                productSell = new Product();
                productSell.ProductId = int.Parse(productsDgv["productId", e.RowIndex].Value.ToString());
                productSell.ProductName = productsDgv["productName", e.RowIndex].Value.ToString();
                productSell.ProductPriceSale = decimal.Parse(productsDgv["productPriceSale", e.RowIndex].Value.ToString());
                productSell.ProductCountAccumulate = count;
                //new add
                productSell.ProductCountSale = count;
                productSell.ProductDimension = productsDgv["productDimension", e.RowIndex].Value.ToString();
                productSell.ProductDescription = productsDgv["productDescription", e.RowIndex].Value.ToString();

                ucSellProduct.txtProductName.Text = productSell.ProductName;
                ucSellProduct.txtDimension.Text = productSell.ProductDimension;
                ucSellProduct.txtDescription.Text = productSell.ProductDescription;
                ucSellProduct.txtProductPriceSale.Text = productSell.ProductPriceSale.ToString("C");
                ucSellProduct.numericUpDownCount.Maximum = productSell.ProductCountAccumulate;

                ucSellProduct.btnProductSell.Click += new EventHandler(btnProductSell_Click);
                ucSellProduct.btnCancel.Click += new EventHandler(btnSplitMainPanel2Cancel_Click);
                /* avaliable
                FrmOrder frmOrder = new FrmOrder(product);
                frmOrder.StartPosition = FormStartPosition.CenterParent;
                frmOrder.ShowDialog(this);
                frmOrder.Dispose();*/
            }
            else
                MessageBox.Show("商品库存不够, 请先添加.");

        }

        private void btnProductSell_Click(object sender, EventArgs e)
        {
            //modify
            productSell.ProductCountSale = int.Parse(ucSellProduct.numericUpDownCount.Value.ToString());
            //new add
            productSell.ProductCountAccumulate = productSell.ProductCountSale;
            //order & orderProduct insert
            Order order = new Order();
            order.OrderByUser = user.NickName;
            order.OrderContact = "游客";
            order.OrderDriveEmployee = "无";
            order.OrderNo = DateTime.Now.ToString("yyMMddHHmmss");
            order.OrderPay = productSell.ProductPriceSale * productSell.ProductCountSale;//modify
            order.OrderPayStatus = true;
            order.OrderTime = DateTime.Now;
            if(new OrderService().Insert(order).OrderId > 0)
            {
                OrderProduct orderProduct = new OrderProduct();
                orderProduct.BuyCount = productSell.ProductCountSale;//modify
                orderProduct.Dimension = productSell.ProductDimension;
                orderProduct.OrderNo = order.OrderNo;
                orderProduct.OrderId = order.OrderId;
                orderProduct.Price = productSell.ProductPriceSale;
                orderProduct.ProductName = productSell.ProductName;
                orderProduct.ProductId = productSell.ProductId;
                if(new OrderProductService().Insert(orderProduct).OrderProductId > 0)
                {
                    //库存--
                    if (productService.UpdateProductCount(productSell))
                    {
                        productsDgv["productCountAccumulate", rowIndexSell].Value = int.Parse(productsDgv["productCountAccumulate", rowIndexSell].Value.ToString()) - productSell.ProductCountAccumulate;
                        productsDgv["ProductCountSale", rowIndexSell].Value = int.Parse(productsDgv["ProductCountSale", rowIndexSell].Value.ToString()) + productSell.ProductCountSale;
                        this.toolStripStatusLabelOPStatus.Text = "下单销售成功.";
                        return;
                    }
                }
                //orderProductService.Insert();
            }
            this.toolStripStatusLabelOPStatus.Text = "下单销售失败";
            //orderService.Insert()
            //成功后关闭 并释放productSell
        }

        private void btnSplitMainPanel2Cancel_Click(object sender, EventArgs e)
        {
            productSell = null;
            this.splitContainerMain.Panel2.Controls.Clear();
        }

        private void UpdateProductDgv(int productType)
        {
            dt = productService.ReadInDataTableByProductType(productType);
            DrawProductsDgv();
        }

        private void productsDgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnPurchaseAdd_Click(object sender, EventArgs e)
        {
            //? Need Add a new purchase first?

            //Add Purchase
        }

        private void clearSplitPanelChildren()
        {
            this.splitContainerTop.Panel1.Controls.Clear();
            this.splitContainerTop.Panel2.Controls.Clear();
            this.splitContainerMain.Panel2.Controls.Clear();
        }

        #region ToolStripMenuItem_Click

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
            //Environment.Exit(0);
        }

        /*
        private void 类别管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //initSplitPanel();
            //this.Update();
            if (this.splitContainerTop.Parent == null)
                this.splitContainerTop.Parent = this.splitContainerMain.Panel1;
            typeMgrTreeView();
            ShowProductsDgv(false);
            //typeMgrEdit();
        }*/

        private void 库存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.splitContainerTop.Parent == null)
                this.splitContainerTop.Parent = this.splitContainerMain.Panel1;
            typeMgrTreeView();
            ShowProductsDgv(false);
        }

        private void 销售ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmOrder frmOrder = new FrmOrder();
            frmOrder.StartPosition = FormStartPosition.CenterScreen;
            frmOrder.ShowDialog(this);
            frmOrder.Dispose();
            this.WindowState = FormWindowState.Minimized;
        }

        //private Form frmPurchase = null;
        private void 进货ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*
            foreach (Control control in this.Controls)
            {
                if (control.Parent == this)
                {
                    Type type = control.GetType();
                    if(type == typeof(MenuStrip) || type == typeof(SplitContainer))
                        continue;
                    this.Controls.Remove(control);
                }
            }*/
            //this.splitContainerTop.Panel2.Controls.Clear();
            /*
             * Support
            this.splitContainerTop.Parent = null;
            clearSplitPanelChildren();
            MessageBox.Show("Purchase");
            */

            //未需要, 但等dialogResult后需要更新
            //this.splitContainerTop.Parent = null;
            //clearSplitPanelChildren();

            //defineInitFrmPurchase();
            FrmPurchase frmPurchase = new FrmPurchase();
            frmPurchase.StartPosition = FormStartPosition.CenterParent;
            DialogResult dlgResult = frmPurchase.ShowDialog();

            //MessageBox.Show(dlgResult.ToString());
            ShowProductsDgv(true);
            //显示所有进货记录, 倒序排序显示.

            /*
            frmPurchase = new Form();
            //Define control
            Button btnPurchaseAdd = new Button();
            btnPurchaseAdd.Text = "添加";
            btnPurchaseAdd.Click += new EventHandler(btnPurchaseAdd_Click);
            //Add control to form
            frmPurchase.Controls.Add(new Button());
            frmPurchase.StartPosition = FormStartPosition.CenterScreen;
            frmPurchase.ShowDialog();*/
            //this.splitContainerMain.Panel1.Controls.Add(null);
            //MessageBox.Show("Purchase");
            //添加完显示所有商品;
        }
        
        #endregion 

        private void timerTime_Tick(object sender, EventArgs e)
        {
            this.lblCurrentTime.Text = DateTime.Now.ToString();
        }

        private void 进货记录查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmRecordView frmRecordView = new FrmRecordView();
            frmRecordView.StartPosition = FormStartPosition.CenterParent;
            frmRecordView.ShowDialog(this);
            frmRecordView.Dispose();
        }

        private void 员工管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmEmployee frmEmployee = new FrmEmployee();
            frmEmployee.StartPosition = FormStartPosition.CenterParent;
            frmEmployee.ShowDialog(this);
            frmEmployee.Dispose();
        }

        private void 客户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmContact frmContact = new FrmContact();
            frmContact.StartPosition = FormStartPosition.CenterParent;
            frmContact.ShowDialog(this);
            frmContact.Dispose();
        }

        private void 价格修改记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmProductPriceChangeRecord frmChangeRecord = new FrmProductPriceChangeRecord();
            frmChangeRecord.StartPosition = FormStartPosition.CenterParent;
            frmChangeRecord.ShowDialog(this);
            frmChangeRecord.Dispose();
        }

        private void 销售记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmSaleRecord frmSaleRecord = new FrmSaleRecord();
            frmSaleRecord.StartPosition = FormStartPosition.CenterParent;
            frmSaleRecord.ShowDialog(this);
            frmSaleRecord.Dispose();
        }

        private void 账户管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAccountMgr frmAccountMgr = new FrmAccountMgr();
            frmAccountMgr.StartPosition = FormStartPosition.CenterParent;
            frmAccountMgr.ShowDialog(this);
            frmAccountMgr.Dispose();
        }

    }
}
